<?php

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\validate\DemoValidate;
use app\common\exception\FailedException;
use app\common\library\CustomLog;
use app\common\library\QueueRedis;
use app\common\model\User;
use support\Redis;
use support\Request;
use support\Response;
use Webman\Event\Event;

class DemoController extends BaseController
{

    public function redisDemo(): Response
    {
        $key = "redisDemo";
        $value = '欢迎来到webman-gii-api';
        if(!Redis::get($key)){
            Redis::setEx($key, 86400, $value);
        }
        $msg = Redis::get($key);
        return json(['code' => 200, 'msg' => $msg ?: "redis fail"]);
    }

    public function exceptionDemo(): Response
    {
        try {
            throw new FailedException("IndexController::Index");
        }catch (\Exception $e){
            CustomLog::eLog($e,"index");
        }
        return json(['code' => 200, 'msg' => 'exceptionDemo']);
    }

    public function validateDemo(Request $request) : Response
    {
        $params = $request->all();
        $this->validate($params, DemoValidate::class . '.hello');
        return json($params);
    }

    public function queueDemo(): Response
    {
        QueueRedis::now('hello', [
            'hello' => 'webman-hello',
            'age' => 9527,
            'key' => "webman-gii-hello-queue-demo"
        ]);
        return json(['code' => 200, 'msg' => 'queueDemo']);
    }

    public function eventDemo(): Response
    {
        Event::emit('hello.event', [
            'hello' => 'webman-eventDemo',
            'age' => 9527,
            'key' => "webman-gii-hello-event-demo"
        ]);
        return json(['code' => 200, 'msg' => 'eventHello']);
    }


    public function modelDemo(): Response
    {
        $func = function($q){
            $q->where('status',1)->whereOr('id',2);
        };
        $res = User::checkBaseInfo([['id','=',2]],"id,username,status,nickname,phone,email,avatar",['status_text'],$func);
        return json(['code' => 200, 'data' => $res]);
    }

}